package com.vcredit.creditcat.service;

import com.vcredit.creditcat.model.Resource;
import com.vcredit.creditcat.persistence.ResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by liaoshengjun on 2017/8/28.
 */
@Service
public class ResourceService {
	@Autowired
	private ResourceMapper resourceMapper;

	/**
	 * 查询用户的按钮权限
	 * @param userId
	 * @return
	 */
	public List<String> findPrivilegesByUserId(long userId,int resourceType){ return resourceMapper.findPrivilegesByUserId(userId,resourceType);}

	/**
	 * 根据名称查询是否存在按钮权限
	 * @param value
	 * @return
	 */
	public int findPrivilegesByValue(String value){
		return resourceMapper.findPrivilegesByValue(value);
	}

	public void insert(Resource resource){
		resourceMapper.insert(resource);
	}

	public List<Resource> find(Resource obj){
		return resourceMapper.find(obj);
	}

	/**
	 * 分类查询所有资源
	 * @param resourceType
	 * @return
	 */
	public List<Resource> findResourcesByTypes(long resourceType){return resourceMapper.findResourcesByTypes(resourceType);}

	public List<Resource> findByUserId(long userId,int resourceType){
		return resourceMapper.findByUserId(userId,resourceType);
	}

	public List<Long> findParentResourceIds(Set<Long> resourceIds){
		return resourceMapper.findParentResourceIds(resourceIds);
	}

	public List<Resource> getAllMenus(){
		List<Resource> menus = resourceMapper.findResourcesByTypes(0L);
		List<Resource> baseMenus=new ArrayList<>();
		for(Resource menu:menus){
			if(menu.getpId()==0){
				baseMenus.add(menu);
			}
		}
		Iterator<Resource> iterator=baseMenus.iterator();
		while(iterator.hasNext()){
			Resource baseMenu=iterator.next();
			List<Resource> childMenus=new ArrayList<>();
			for(Resource menu:menus){
				if(menu.getpId()==baseMenu.getId()){
					childMenus.add(menu);
				}
			}
			baseMenu.setResources(childMenus);
			if(baseMenu.getResources().size()==0){
				iterator.remove();
			}
		}
		return baseMenus;
	}
}
